package xhr;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/XHRServlet")
public class XHRServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	 private String[] users = {"张三", "李四", "王五"};
       

    public XHRServlet() {
        
    }

	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	public void destroy() {
		// TODO Auto-generated method stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  response.setContentType("text/html;charset=utf-8");
          
          String[] news = {"新闻1", "新闻2", "新闻3"};
          String[] colors = {"pink", "lightgreen", "orange"};
            
          int index = (int) (Math.random() * news.length);
          String title = news[index];
          String color = colors[index];
            
          response.getWriter().write("<h3 style=\"color=" + color + "\">" + title + "</h3>");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 
        request.setCharacterEncoding("UTF-8");
        
        response.setContentType("text/html;charset=UTF-8");
       
        String todo = request.getParameter("todo");
        System.out.println("todo: " + todo);
       
        if ("check".equals(todo)) {
            
            String username = request.getParameter("username");
            System.out.println("用户填入的 username: " + username);
            
            boolean flag = false;
            for (String user : users) {
                if (user.equals(username)) {
                    flag = true;
                    break;
                }
            }
           
            if (flag) {
                System.out.println(username + " 已存在");
                response.getWriter().write("用户名已存在");
            } else {
                System.out.println(username + " 可用");
                response.getWriter().write("用户名可用");
            }
        } else if ("register".equals(todo)) {
       
            response.getWriter().write("注册成功");
            System.out.println("用户注册新账号：" + request.getParameter("username"));
        }
    }
}

